﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.EnterpriseServices;
using System.Web.Services;

public partial class DeliverGoodsManagement_SettlementDetails : System.Web.UI.Page
{
    private string Code
    {
        get
        {
            return Request.QueryString["Code"] != null ? Request.QueryString["Code"].ToString() : "";
        }
    }

    private List<Model.PAYDOCDETAIL> PayDocDetails
    {
        get
        {
            List<Model.PAYDOCDETAIL> payDocDetails = null;
            if (ViewState["PayDocDetails"] != null)
            {
                payDocDetails = (List<Model.PAYDOCDETAIL>)ViewState["PayDocDetails"];
            }
            return payDocDetails;
        }
        set
        {
            ViewState["PayDocDetails"] = value;
        }
    }

    private string CustomerId
    {
        get 
        {
            string id = "";
            if (ViewState["CustomerId"] != null)
            {
                id = ViewState["CustomerId"].ToString();
            }
            return id;
        }
        set 
        {
            ViewState["CustomerId"] = value;
        }
    }

    private string ClearType
    {
        get
        {
            string type = "";
            if (ViewState["ClearType"] != null)
            {
                type = ViewState["ClearType"].ToString();
            }
            return type;
        }
        set
        {
            ViewState["ClearType"] = value;
        }
    }

    private string IsCheck
    {
        get
        {
            string isCheck = "";
            if (ViewState["IsCheck"] != null)
            {
                isCheck = ViewState["IsCheck"].ToString();
            }
            return isCheck;
        }
        set
        {
            ViewState["IsCheck"] = value;
        }
    }

    private List<Model.PAYDOCPAYDETAIL> PayDocPayDetails
    {
        get
        {
            List<Model.PAYDOCPAYDETAIL> dstPayDocPayDetails = null;
            if (ViewState["PayDocPayDetails"] != null)
            {
                dstPayDocPayDetails = (List<Model.PAYDOCPAYDETAIL>)ViewState["PayDocPayDetails"];
            }
            return dstPayDocPayDetails;
        }
        set
        {
            ViewState["PayDocPayDetails"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("700100");
        if (!IsPostBack)
        {
            BindPayDoc();
            BindPayDocDetail();
            BindPayDocPayDetail();
            if (this.IsCheck == "1")
            {
                btnAddPayDocPayDetail.Visible = false;
                btnGetOrder.Visible = false;
                btnAudit.Enabled = false;
                btnSave.Enabled = false;
                btnCancel.Enabled = false;
                btnDelete.Enabled = false;
            }
            //else if (this.IsCheck == "0")
            //{
            //    btnAddPayDocPayDetail.Visible = true;
            //    btnGetOrder.Visible = true;
                
            //}
            btnDelete.Attributes.Add("onclick", "if(!confirm('确定要删除本结算单？'))return false;");
        }
    }

    private void BindPayDoc()
    {
        DataSet dst = new BLL.PAYDOC().GetPayDocByID(this.Code);
        if (dst != null && dst.Tables.Count > 0 && dst.Tables[0].Rows.Count>0)
        {
            this.CustomerId = dst.Tables[0].Rows[0]["PD_CUSTOMERCODE"].ToString();
            hidCustomerId.Value = this.CustomerId;
            this.ClearType = dst.Tables[0].Rows[0]["PD_CLEARTYPE"].ToString();
            this.IsCheck = dst.Tables[0].Rows[0]["PD_CHECK"].ToString();
            dlistPayDoc.DataSource = dst;
            dlistPayDoc.DataBind();
            
        }
        else
        {
            Response.Write("<script>alert('系统无此结算单信息！');location.href='Settlement.aspx';</script>");
        }
    }

    private void BindPayDocDetail()
    {
        int pageCount, recordCount;
        this.PayDocDetails = new BLL.PAYDOCDETAIL().GetList(1000, 1, "PDD_DOCTYPE", true, " and PDD_ID='" + this.Code + "'", out pageCount, out recordCount);
        this.PayDocDetails = new BLL.PAYDOCDETAIL().GetTempPayDocDetails(this.PayDocDetails, this.CustomerId);
        dlistPayDocDetail.DataSource = this.PayDocDetails;
        dlistPayDocDetail.DataBind();
        new BLL.PAYDOCDETAIL().ClearSession();
    }

    private void ReBindPayDocDetail()
    {
        dlistPayDocDetail.DataSource = this.PayDocDetails;
        dlistPayDocDetail.DataBind();
    }

    private void BindPayDocPayDetail()
    {
        int pageCount, recordCount;
        this.PayDocPayDetails = new BLL.PAYDOCPAYDETAIL().GetList(1000, 1, "PDPD_PAYDATE", true, " and PDPD_ID='" + this.Code + "'", out pageCount, out recordCount);
        dlistPayDocPayDetail.DataSource = this.PayDocPayDetails;
        dlistPayDocPayDetail.DataBind();
    }

    private void RebindPayDocPayDetail()
    {
        dlistPayDocPayDetail.DataSource = this.PayDocPayDetails;
        dlistPayDocPayDetail.DataBind();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (!Check.CheckPermission("700100", "00002"))
            {
                Share.Alert(this.Page, "无权操作"); return;
            }
            Model.PAYDOC payDoc = new BLL.PAYDOC().GetModel(this.Code);
            if (payDoc == null)
            {
                Response.Write("<script>alert('读取数据时出现错误请重新保存！');</script>");
                return;
            }

            if (payDoc.PD_CHECK == 1)
            {
                Share.Alert(this.Page, "已经审核过的结算单不允许被修改！"); return;
            }

            #region 不含担保交易
            if (payDoc.PD_SECDEAL == 0)
            {
                TextBox txtSettleAmount;
                TextBox txtPayAmount;
                TextBox txtSubAmount;
                TextBox txtNotes;
                foreach (DataListItem tempItem in dlistPayDoc.Items)
                {
                    txtSettleAmount = (TextBox)tempItem.FindControl("txtSettleAmount");
                    txtPayAmount = (TextBox)tempItem.FindControl("txtPayAmount");
                    txtSubAmount = (TextBox)tempItem.FindControl("txtSubAmount");
                    txtNotes = (TextBox)tempItem.FindControl("txtNotes");

                    payDoc.PD_CAMT = Convert.ToDecimal(txtSettleAmount.Text.Trim());
                    payDoc.PD_PAMT = Convert.ToDecimal(txtPayAmount.Text.Trim());
                    payDoc.PD_SUBAMT = Convert.ToDecimal(txtSubAmount.Text.Trim());
                    payDoc.PD_NOTE = txtNotes.Text.Trim();
                }

                TextBox txtAmount;
                TextBox txtSubAmt;
                TextBox txtNote;
                for (int i = 0; i < this.PayDocDetails.Count; i++)
                {
                    txtAmount = (TextBox)dlistPayDocDetail.Items[i].FindControl("txtAmount");
                    txtSubAmt = (TextBox)dlistPayDocDetail.Items[i].FindControl("txtSubAmount");
                    txtNote = (TextBox)dlistPayDocDetail.Items[i].FindControl("txtNotes");

                    this.PayDocDetails[i].PDD_AMT = Convert.ToDecimal(txtAmount.Text.Trim());
                    this.PayDocDetails[i].PDD_SUBAMT = Convert.ToDecimal(txtSubAmt.Text.Trim());
                    this.PayDocDetails[i].PDD_NOTE = txtNote.Text.Trim();
                }

                SavePayDocPayDetail(this.PayDocPayDetails, payDoc.PD_CLEARTYPE);

                bool result = new BLL.PAYDOC().UpdatePayDoc(payDoc, this.PayDocDetails, this.PayDocPayDetails);
                if (result)
                {
                    Share.Alert(this.Page, "修改成功！");
                }
                else
                {
                    Share.Alert(this.Page, "修改失败！");
                }
            }
            #endregion
            #region 含担保交易
            else if (payDoc.PD_SECDEAL == 1)
            {
                TextBox txtSettleAmount;
                TextBox txtPayAmount;
                TextBox txtSubAmount;
                TextBox txtNotes;
                foreach (DataListItem tempItem in dlistPayDoc.Items)
                {
                    txtSettleAmount = (TextBox)tempItem.FindControl("txtSettleAmount");
                    txtPayAmount = (TextBox)tempItem.FindControl("txtPayAmount");
                    txtSubAmount = (TextBox)tempItem.FindControl("txtSubAmount");
                    txtNotes = (TextBox)tempItem.FindControl("txtNotes");

                    payDoc.PD_CAMT = Convert.ToDecimal(txtSettleAmount.Text.Trim());
                    payDoc.PD_PAMT = Convert.ToDecimal(txtPayAmount.Text.Trim());
                    payDoc.PD_SUBAMT = Convert.ToDecimal(txtSubAmount.Text.Trim());
                    payDoc.PD_NOTE = txtNotes.Text.Trim();
                }

                SavePayDocPayDetail(this.PayDocPayDetails, "003");

                bool result = new BLL.PAYDOC().UpdatePayDoc(payDoc, null, this.PayDocPayDetails);
                if (result)
                {
                    Share.Alert(this.Page, "修改成功！");
                }
                else
                {
                    Share.Alert(this.Page, "修改失败！");
                }
            }
            #endregion
        }
        catch (FormatException ex)
        {
            Share.Alert(this.Page, "请输入正确格式的数据！");
        }
        catch(Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    protected void btnAudit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("700100", "00010"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        int result = Audit(this.Code, Share.UserValue(0));
        switch (result)
        {
            case 0:
                Share.Alert(this.Page, "系统无法查找到该结算单的结算单支付明细");
                break;
            case 1:
                Share.Alert(this.Page, "系统无法查找到该结算单的结算单支付明细");
                break;
            case 2:
                Share.Alert(this.Page, "结算单主表中支付金额不等于结算单支付明细的汇总支付金额");
                break;
            case 3:
                Share.Alert(this.Page, "结算单的结算金额大于支付金额");
                break;
            case 4:
                Share.Alert(this.Page, "结算类型有错误");
                break;
            case 5:
                Share.Alert(this.Page, "结算单审核成功");
                BindPayDoc();
                BindPayDocDetail();
                BindPayDocPayDetail();
                if (this.IsCheck == "1")
                {
                    btnAddPayDocPayDetail.Visible = false;
                    btnGetOrder.Visible = false;
                    btnAudit.Enabled = false;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                }
                //else if (this.IsCheck == "0")
                //{
                //    btnAddPayDocPayDetail.Visible = true;
                //    btnGetOrder.Visible = true;
                //}
                break;
            case 6:
                Share.Alert(this.Page, "提交结算单审核失败");
                break;
            case 7:
                Share.Alert(this.Page, "系统无法查找到该结算单的结算明细");
                break;
            case 8:
                Share.Alert(this.Page, "系统无法查找到该结算单的结算明细");
                break;
            case 9:
                Share.Alert(this.Page, "系统无法查找到该结算单");
                break;
            case 10:
                Share.Alert(this.Page, "无法重复审核已审核过的结算单");
                break;
            case 11:
                Share.Alert(this.Page,"系统无法找到该会员的VIP信息！");
                break;
            case 12:
                Share.Alert(this.Page, "系统无法找到该会员的结余金额信息！");
                break;
            case 13:
                Share.Alert(this.Page, "系统无法找到该会员的结余金额信息！");
                break;
            case 14:
                Share.Alert(this.Page, "系统无法找到该会员的结余金额信息！");
                break;
            case 15:
                Share.Alert(this.Page, "系统无法确定该结算单是否含担保交易！");
                break;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="payDocId"></param>
    /// <returns></returns>
    public int Audit(string payDocId, string userId)
    {
        Model.PAYDOC payDoc = new BLL.PAYDOC().GetModel(payDocId);

        if (payDoc == null)
        {
            return 9; //系统无法查找到该结算单
        }

        if (payDoc.PD_CHECK == 1)
        {
            return 10; //该结算单已被审核过
        }

        Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(payDoc.PD_CUSTOMERCODE);
        if (userInfo == null)
        {
            return 11;
        }
        Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);
        if (userAccount == null)
        {
            return 12;
        }

        #region 不含担保交易
        if (payDoc.PD_SECDEAL == 0)
        {

            


            if (payDoc.PD_PAMT != 0)
            {
                IList<Model.PAYDOCPAYDETAIL> payDocPayDetails = new SQLServerDAL.PAYDOCPAYDETAIL().GetPayDocPayDetailByPDD_ID(payDocId);
                if (payDocPayDetails == null)
                {
                    return 0; //系统无法查找到该结算单的结算单支付明细
                }
                if (payDocPayDetails.Count == 0)
                {
                    return 1; //返回值为1时表示无结算单支付明细
                }

                decimal payAmount = 0;
                decimal usableDeliverAmount = userInfo.BYZD13;
                foreach (Model.PAYDOCPAYDETAIL temp in payDocPayDetails)
                {
                    payAmount += temp.PDPD_PAYAMT;

                    if (temp.PDPD_DTCODE == "001")
                    {
                        if (temp.PDPD_DEALID == "" || temp.PDPD_DEALDATE == null || temp.PDPD_DEALDATE == DateTime.MinValue)
                        {
                            return 13;
                        }
                    }
                    else if (temp.PDPD_DTCODE == "002")
                    {
                        if (temp.PDPD_DEALID == "" || temp.PDPD_DEALDATE == null || temp.PDPD_DEALDATE == DateTime.MinValue)
                        {
                            return 13;
                        }
                    }
                    else if (temp.PDPD_DTCODE == "003")
                    {
                        usableDeliverAmount -= temp.PDPD_PAYAMT;
                        if (usableDeliverAmount < 0)
                        {
                            return 14;
                        }
                    }
                }

                if (payDoc.PD_PAMT != payAmount)
                {
                    return 2; //返回值为2时表示结算单主表中支付金额不等于结算单支付明细的汇总支付金额
                }

                if (payDoc.PD_PAMT < payDoc.PD_CAMT)
                {
                    return 3; //返回值为3时结算单的结算金额大于支付金额
                }
            }

            if (payDoc.PD_CLEARTYPE == "001")
            {
                int pageCount, recordCount;
                List<Model.PAYDOCDETAIL> payDocDetails = new BLL.PAYDOCDETAIL().GetList(1000, 1, "PDD_DOCDATE", true, " and PDD_ID='" + payDocId + "'", out pageCount, out recordCount);
                if (payDocDetails != null)
                {
                    if (payDocDetails.Count > 0)
                    {
                        StringBuilder strSql = new StringBuilder();
                        StringBuilder strSqlOfErp = new StringBuilder();
                        decimal pointCountOfOrderDoc = 0;
                        decimal pointCountOfReturnDoc = 0;
                        foreach (Model.PAYDOCDETAIL temp in payDocDetails)
                        {
                            if (temp.PDD_DOCTYPE == "001")
                            {
                                if (temp.PDD_SUBAMT == 0)
                                {
                                    strSql.Append("update OrderDoc set ORDER_CLEARAMT=ORDER_CLEARAMT+");
                                    strSql.Append(temp.PDD_AMT);
                                    strSql.Append(",ORDER_CLEAR=1 where ORDER_ID='");
                                    strSql.Append(temp.PDD_DOCID);
                                    strSql.Append("'|");
                                }
                                else
                                {
                                    strSql.Append("update OrderDoc set ORDER_CLEARAMT=ORDER_CLEARAMT+");
                                    strSql.Append(temp.PDD_AMT);
                                    strSql.Append(" where ORDER_ID='");
                                    strSql.Append(temp.PDD_DOCID);
                                    strSql.Append("'|");
                                }
                                pointCountOfOrderDoc += temp.PDD_AMT * (new BLL.V_VIPSET().GetBaseBS(payDoc.PD_CUSTOMERCODE));

                            }
                            else if (temp.PDD_DOCTYPE == "002")
                            {
                                if (temp.PDD_SUBAMT == 0)
                                {
                                    strSql.Append("update RETURNDOC set RD_CLEAREDAMT=RD_CLEAREDAMT+");
                                    strSql.Append(-1 * temp.PDD_AMT);
                                    strSql.Append(",RD_CLEAR=1 where RD_ID='");
                                    strSql.Append(temp.PDD_DOCID);
                                    strSql.Append("'|");
                                }
                                else
                                {
                                    strSql.Append("update RETURNDOC set RD_CLEAREDAMT=RD_CLEAREDAMT+");
                                    strSql.Append(-1 * temp.PDD_AMT);
                                    strSql.Append(" where RD_ID='");
                                    strSql.Append(temp.PDD_DOCID);
                                    strSql.Append("'|");
                                }
                                Model.RETURNDOC returnDoc = new BLL.RETURNDOC().GetModel(temp.PDD_DOCID);
                                if (returnDoc != null)
                                {
                                    pointCountOfReturnDoc += (temp.PDD_AMT / temp.PDD_TAMT) * returnDoc.RD_SUBITG;
                                }

                            }
                        }

                        strSql.Append("update paydoc set pd_check=1,pd_checker='");
                        strSql.Append(userId);
                        strSql.Append("',pd_checkdate='");
                        strSql.Append(DateTime.Now);
                        strSql.Append("' where pd_id='");
                        strSql.Append(payDocId);
                        strSql.Append("'|");

                        decimal count = 0;
                        for (int i = 0; i < this.PayDocPayDetails.Count; i++)
                        {
                            if (this.PayDocPayDetails[i].PDPD_PAYTYPE == "200")
                            {
                                count += this.PayDocPayDetails[i].PDPD_PAYAMT;
                            }

                        }



                        string str1 = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, pointCountOfReturnDoc + pointCountOfOrderDoc, payDoc.PD_CUSTOMERCODE);
                        strSql.Append(str1);
                        strSqlOfErp.Append(str1);

                        string str2 = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(payDoc.PD_SUBAMT + count * -1, userInfo.DM);
                        strSql.Append(str2);
                        strSqlOfErp.Append(str2);

                        strSql.Append("update V_VIPSET set BYZD13=(select BYZD12 from v_vipset where GKDM='");
                        strSql.Append(payDoc.PD_CUSTOMERCODE);
                        strSql.Append("')+(select DQJE_1 from v_vip_account where dm='");
                        strSql.Append(userInfo.DM);
                        strSql.Append("') where GKDM='");
                        strSql.Append(payDoc.PD_CUSTOMERCODE);
                        strSql.Append("'|");

                        strSqlOfErp.Append("update V_VIPSET set BYZD13=(select BYZD12 from v_vipset where GKDM='");
                        strSqlOfErp.Append(payDoc.PD_CUSTOMERCODE);
                        strSqlOfErp.Append("')+(select DQJE_1 from v_vip_account where dm='");
                        strSqlOfErp.Append(userInfo.DM);
                        strSqlOfErp.Append("') where GKDM='");
                        strSqlOfErp.Append(payDoc.PD_CUSTOMERCODE);
                        strSqlOfErp.Append("'|");

                        LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                        bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), StringBuilderToStringArray(strSql), StringBuilderToStringArray(strSqlOfErp));


                        if (result)
                        {
                            return 5; //返回值为5时表示结算单审核成功
                        }
                        else
                        {
                            return 6; //返回值为6时表示提交结算单审核失败
                        }

                    }
                    else
                    {
                        return 7; //返回值为7时表示无结算单明细
                    }
                }
                else
                {
                    return 8; //系统无法查找到该结算单
                }
            }
            #region 预收款
            else if (payDoc.PD_CLEARTYPE == "002")
            {
                StringBuilder strSql = new StringBuilder();
                StringBuilder strSqlOfErp = new StringBuilder();

                strSql.Append("update paydoc set pd_check=1,pd_checker='");
                strSql.Append(userId);
                strSql.Append("',pd_checkdate='");
                strSql.Append(DateTime.Now);
                strSql.Append("' where pd_id='");
                strSql.Append(payDocId);
                strSql.Append("'|");

                string str1 = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(payDoc.PD_SUBAMT, 0, 0, payDoc.PD_CUSTOMERCODE);
                strSql.Append(str1);
                strSqlOfErp.Append(str1);

                string str2 = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(payDoc.PD_SUBAMT, userInfo.DM);
                strSql.Append(str2);
                strSqlOfErp.Append(str2);

                LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), StringBuilderToStringArray(strSql), StringBuilderToStringArray(strSqlOfErp));

                if (result)
                {
                    return 5; //返回值为5时表示结算单审核成功
                }
                else
                {
                    return 6; //返回值为6时表示提交结算单审核失败
                }
            }
	        #endregion
            else
            {
                return 4; //返回值为4时表示结算类型有错误
            }
        }
        #endregion
        #region 含担保交易
        else if (payDoc.PD_SECDEAL == 1)
        {
            IList<Model.PAYDOCPAYDETAIL> payDocPayDetails = new SQLServerDAL.PAYDOCPAYDETAIL().GetPayDocPayDetailByPDD_ID(payDocId);
            if (payDocPayDetails == null)
            {
                return 0; //系统无法查找到该结算单的结算单支付明细
            }
            if (payDocPayDetails.Count == 0)
            {
                return 1; //返回值为1时表示无结算单支付明细
            }

            decimal payAmount = 0;

            foreach (Model.PAYDOCPAYDETAIL temp in payDocPayDetails)
            {
                payAmount += temp.PDPD_PAYAMT;
            }

            if (payDoc.PD_PAMT != payAmount)
            {
                return 2; //返回值为2时表示结算单主表中支付金额不等于结算单支付明细的汇总支付金额
            }

            if (payDoc.PD_PAMT > payDoc.PD_CAMT)
            {
                return 3; //返回值为3时结算单的结算金额大于支付金额
            }

            int pageCount, recordCount;
            List<Model.PAYDOCDETAIL> payDocDetails = new BLL.PAYDOCDETAIL().GetList(1000, 1, "PDD_DOCDATE", true, " and PDD_ID='" + payDocId + "'", out pageCount, out recordCount);
            if (payDocDetails != null)
            {
                if (payDocDetails.Count > 0)
                {
                    StringBuilder strSql = new StringBuilder();
                    StringBuilder strSqlOfErp = new StringBuilder();
                    string orderId = "";

                    decimal pointCountOfReturnDoc = 0;
                    foreach (Model.PAYDOCDETAIL temp in payDocDetails)
                    {

                        if (temp.PDD_SUBAMT == 0)
                        {
                            strSql.Append("update RETURNDOC set RD_CLEAREDAMT=RD_CLEAREDAMT+");
                            strSql.Append(-1 * temp.PDD_AMT);
                            strSql.Append(",RD_CLEAR=1 where RD_ID='");
                            strSql.Append(temp.PDD_DOCID);
                            strSql.Append("'|");

                            
                        }
                        else
                        {
                            strSql.Append("update RETURNDOC set RD_CLEAREDAMT=RD_CLEAREDAMT+");
                            strSql.Append(-1 * temp.PDD_AMT);
                            strSql.Append(" where RD_ID='");
                            strSql.Append(temp.PDD_DOCID);
                            strSql.Append("'|");
                        }
                        Model.RETURNDOC returnDoc = new BLL.RETURNDOC().GetModel(temp.PDD_DOCID);
                        if (returnDoc != null)
                        {
                            pointCountOfReturnDoc += (temp.PDD_AMT / temp.PDD_TAMT) * returnDoc.RD_SUBITG;
                            orderId = returnDoc.RD_DOCID;
                            strSql.Append("update orderdoc set ORDER_CLEARAMT = ORDER_CLEARAMT+");
                            strSql.Append(-1 * temp.PDD_AMT);
                            strSql.Append(" where ORDER_ID='");
                            strSql.Append(returnDoc.RD_DOCID);
                            strSql.Append("'|");
                        }
                    }

                    strSql.Append("update paydoc set pd_check=1,pd_checker='");
                    strSql.Append(userId);
                    strSql.Append("',pd_checkdate='");
                    strSql.Append(DateTime.Now);
                    strSql.Append("' where pd_id='");
                    strSql.Append(payDocId);
                    strSql.Append("'|");

                    decimal count = 0;
                    for (int i = 0; i < this.PayDocPayDetails.Count; i++)
                    {
                        if (this.PayDocPayDetails[i].PDPD_DTCODE == "003")
                        {
                            count += this.PayDocPayDetails[i].PDPD_PAYAMT;
                        }
                        else if (this.PayDocPayDetails[i].PDPD_DTCODE == "002")
                        {
                            strSql.Append("update paydetail set PD_HRAMT=PD_HRAMT+");
                            strSql.Append(this.PayDocPayDetails[i].PDPD_PAYAMT * -1);
                            strSql.Append(" where PD_ID='");
                            strSql.Append(orderId);
                            strSql.Append("' and PD_DETAILID='");
                            strSql.Append(this.PayDocPayDetails[i].PDPD_PAYDETAILID);
                            strSql.Append("'|");
                        }
                    }



                    string str1 = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, pointCountOfReturnDoc, payDoc.PD_CUSTOMERCODE);
                    strSql.Append(str1);
                    strSqlOfErp.Append(str1);

                    string str2 = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(payDoc.PD_SUBAMT + count * -1, userInfo.DM);
                    strSql.Append(str2);
                    strSqlOfErp.Append(str2);

                    strSql.Append("update V_VIPSET set BYZD13=(select BYZD12 from v_vipset where GKDM='");
                    strSql.Append(payDoc.PD_CUSTOMERCODE);
                    strSql.Append("')+(select DQJE_1 from v_vip_account where dm='");
                    strSql.Append(userInfo.DM);
                    strSql.Append("') where GKDM='");
                    strSql.Append(payDoc.PD_CUSTOMERCODE);
                    strSql.Append("'|");

                    strSqlOfErp.Append("update V_VIPSET set BYZD13=(select BYZD12 from v_vipset where GKDM='");
                    strSqlOfErp.Append(payDoc.PD_CUSTOMERCODE);
                    strSqlOfErp.Append("')+(select DQJE_1 from v_vip_account where dm='");
                    strSqlOfErp.Append(userInfo.DM);
                    strSqlOfErp.Append("') where GKDM='");
                    strSqlOfErp.Append(payDoc.PD_CUSTOMERCODE);
                    strSqlOfErp.Append("'|");

                    LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                    bool result = webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), StringBuilderToStringArray(strSql), StringBuilderToStringArray(strSqlOfErp));


                    if (result)
                    {
                        return 5; //返回值为5时表示结算单审核成功
                    }
                    else
                    {
                        return 6; //返回值为6时表示提交结算单审核失败
                    }
                }
                else
                {
                    return 7; //返回值为7时表示无结算单明细
                }
            }
            else
            {
                return 8; //系统无法查找到该结算单
            }
        }
        #endregion
        
        else
        {
            return 15;
        }
    }

    private string[] StringBuilderToStringArray(StringBuilder strSql)
    {
        string stringSql = strSql.ToString();
        char[] charToTrim = new char[] { '|' };
        return stringSql.TrimEnd(charToTrim).Split(charToTrim);
    }

    protected void dlistPayDocDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "deleteitem")
        {
            if (this.IsCheck != "0")
            {
                Share.Alert(this.Page, "已经审核过的结算单不允许修改！"); return;
            }
            this.PayDocDetails.RemoveAt(e.Item.ItemIndex);
            ReBindPayDocDetail();
        }
        else if (e.CommandName.ToLower() == "upt")
        {
            decimal payAmount = 0;
            foreach (DataListItem tempItem in dlistPayDocDetail.Items)
            {
                TextBox txtItem = (TextBox)tempItem.FindControl("txtAmount");
                payAmount += Convert.ToDecimal(txtItem.Text.Trim());
            }

            TextBox txtSettleAmount = (TextBox)dlistPayDoc.Items[0].FindControl("txtSettleAmount");
            TextBox txtPayAmount = (TextBox)dlistPayDoc.Items[0].FindControl("txtPayAmount");
            TextBox txtSubAmount = (TextBox)dlistPayDoc.Items[0].FindControl("txtSubAmount");

            TextBox txtSubAmount1 = (TextBox)e.Item.FindControl("txtSubAmount");
            TextBox txtAmount = (TextBox)e.Item.FindControl("txtAmount");
            Label txtTotal = (Label)e.Item.FindControl("txtTotal");
            Label txtSettleAmount1 = (Label)e.Item.FindControl("txtSettleAmount");

            if (Convert.ToDecimal(txtTotal.Text) - Convert.ToDecimal(txtSettleAmount1.Text) < Convert.ToDecimal(txtAmount.Text))
            {
                Share.Alert(this.Page,"本次结算金额必须小于等于订单总金额与订单已结算金额之差！");
                return;
            }

            txtSettleAmount.Text = String.Format("{0:0.00}", payAmount);
            txtSubAmount.Text = String.Format("{0:0.00}", Convert.ToDecimal(txtPayAmount.Text) - Convert.ToDecimal(txtSettleAmount.Text));
            txtSubAmount1.Text =String.Format("{0:0.00}", Convert.ToDecimal(txtTotal.Text)-Convert.ToDecimal(txtSettleAmount1.Text)-Convert.ToDecimal(txtAmount.Text));
            
        }
    }

    private void BindDropPayType(DropDownList drop)
    {
        drop.DataSource = new BLL.PAYTYPE().GetAllList();
        drop.DataTextField = "PT_NAME";
        drop.DataValueField = "PT_CODE";
        drop.DataBind();
    }

    protected void dlistPayDocPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {

            DropDownList drop = (DropDownList)e.Item.FindControl("dropPayType");
            TextBox txtPayAmount = (TextBox)e.Item.FindControl("txtPayAmount");
            //TextBox txtPayDate = (TextBox)e.Item.FindControl("txtPayDate");
            TextBox txtDealId = (TextBox)e.Item.FindControl("txtDealId");
            TextBox txtDealDate = (TextBox)e.Item.FindControl("txtDealDate");
            TextBox txtAccount = (TextBox)e.Item.FindControl("txtAccount");
            TextBox txtNotes = (TextBox)e.Item.FindControl("txtNotes");
            Button btnDelete = (Button)e.Item.FindControl("btnDelete");
            if (drop != null)
            {
                BindDropPayType(drop);
                for (int i = 0; i < drop.Items.Count; i++)
                {
                    if (drop.Items[i].Value == this.PayDocPayDetails[e.Item.ItemIndex].PDPD_PAYTYPE)
                    {
                        drop.SelectedIndex = i;
                        break;
                    }
                }
            }
            if (this.IsCheck == "1")
            {
                drop.Enabled = false;
                txtPayAmount.Enabled = false;
                //txtPayDate.Enabled = false;
                txtDealId.Enabled = false;
                txtDealDate.Enabled = false;
                txtAccount.Enabled = false;
                txtNotes.Enabled = false;
                btnDelete.Enabled = false;
            }

            Button btnUpdatePayAmount = (Button)e.Item.FindControl("btnUpdatePayAmount");
            txtPayAmount.Attributes.Add("onblur", btnUpdatePayAmount.ClientID + ".click();");
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("SettlementDetails.aspx?code="+this.Code);
    }

    protected void btnAddPayDocPayDetail_Click(object sender, EventArgs e)
    {
        if (this.IsCheck != "0")
        {
            Share.Alert(this.Page, "已经审核过的结算单不允许修改！"); return;
        }
        SavePayDocPayDetail(this.PayDocPayDetails,this.ClearType);
        Model.PAYDOCPAYDETAIL payDocPayDetail = new Model.PAYDOCPAYDETAIL();
        payDocPayDetail.PDPD_DEALDATE = DateTime.Now;
        payDocPayDetail.PDPD_PAYDATE = DateTime.Now;
        this.PayDocPayDetails.Add(payDocPayDetail);
        RebindPayDocPayDetail();
    }

    public void SavePayDocPayDetail(List<Model.PAYDOCPAYDETAIL> payDocPayDetails,string clearType)
    {
        try
        {
            DropDownList dropPayType;
            TextBox txtPayAmount;
            ///TextBox txtPayDate;
            TextBox txtDealID;
            TextBox txtDealDate;
            TextBox txtAccount;
            TextBox txtNotes;

            if (clearType == "002")
            {
                for (int i = 0; i < payDocPayDetails.Count; i++)
                {
                    dropPayType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropPayType");
                    txtPayAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
                    //txtPayDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayDate");
                    txtDealID = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealID");
                    txtDealDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealDate");
                    txtAccount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtAccount");
                    txtNotes = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtNotes");

                    if (dropPayType.SelectedValue == "200")
                    {
                        throw new Exception("预收款支付方式不能选择账户余额！");
                    }

                    payDocPayDetails[i].PDPD_PAYTYPE = dropPayType.SelectedItem.Value;
                    payDocPayDetails[i].PDPD_PAYAMT = Convert.ToDecimal(txtPayAmount.Text.Trim());
                    //payDocPayDetails[i].PDPD_PAYDATE = Convert.ToDateTime(txtPayDate.Text.Trim());
                    payDocPayDetails[i].PDPD_DEALID = txtDealID.Text.Trim();
                    payDocPayDetails[i].PDPD_DEALDATE = Convert.ToDateTime(txtDealDate.Text.Trim());
                    payDocPayDetails[i].PDPD_ACCOUNT = txtAccount.Text.Trim();
                    payDocPayDetails[i].PDPD_NOTE = txtNotes.Text.Trim();
                }

            }
            else if (clearType == "001")
            {
                decimal count = 0;
                for (int i = 0; i < payDocPayDetails.Count; i++)
                {
                    dropPayType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropPayType");
                    txtPayAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
                    //txtPayDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayDate");
                    txtDealID = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealID");
                    txtDealDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealDate");
                    txtAccount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtAccount");
                    txtNotes = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtNotes");

                    payDocPayDetails[i].PDPD_PAYTYPE = dropPayType.SelectedItem.Value;
                    payDocPayDetails[i].PDPD_PAYAMT = Convert.ToDecimal(txtPayAmount.Text.Trim());
                    //payDocPayDetails[i].PDPD_PAYDATE = Convert.ToDateTime(txtPayDate.Text.Trim());
                    payDocPayDetails[i].PDPD_DEALID = txtDealID.Text.Trim();
                    payDocPayDetails[i].PDPD_DEALDATE = Convert.ToDateTime(txtDealDate.Text.Trim());
                    payDocPayDetails[i].PDPD_ACCOUNT = txtAccount.Text.Trim();
                    payDocPayDetails[i].PDPD_NOTE = txtNotes.Text.Trim();

                    if (dropPayType.SelectedValue == "200")
                    {
                        count += payDocPayDetails[i].PDPD_PAYAMT;
                    }

                }
                if (count > 0)
                {
                    Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(this.CustomerId);
                    if (userInfo == null)
                    {
                        throw new Exception("未找到会员VIP信息");
                    }
                    Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);
                    if (userAccount == null)
                    {
                        throw new Exception("未找到会员结余款信息");
                    }
                    if (userAccount.DQJE_1 < count)
                    {
                        throw new Exception("结余金额不足");
                    }
                }
            }
            else if (clearType == "003")
            {
                for (int i = 0; i < payDocPayDetails.Count; i++)
                {
                    dropPayType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropPayType");
                    txtPayAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
                    
                    txtDealID = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealID");
                    txtDealDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealDate");
                    txtAccount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtAccount");
                    txtNotes = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtNotes");

                    if (Convert.ToDecimal(txtPayAmount.Text.Trim())>0)
                    {
                        throw new Exception("请填写数值为负数的金额！");
                    }

                    payDocPayDetails[i].PDPD_PAYTYPE = dropPayType.SelectedItem.Value;
                    payDocPayDetails[i].PDPD_PAYAMT = Convert.ToDecimal(txtPayAmount.Text.Trim());
                    
                    payDocPayDetails[i].PDPD_DEALID = txtDealID.Text.Trim();
                    payDocPayDetails[i].PDPD_DEALDATE = Convert.ToDateTime(txtDealDate.Text.Trim());
                    payDocPayDetails[i].PDPD_ACCOUNT = txtAccount.Text.Trim();
                    payDocPayDetails[i].PDPD_NOTE = txtNotes.Text.Trim();
                }
            }
            
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    public void RemovePayDocPayDetail(int index)
    {
        this.PayDocPayDetails.RemoveAt(index);
    }

    protected void dlistPayDocPayDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "del")
        {
            if (this.IsCheck != "0")
            {
                Share.Alert(this.Page, "已经审核过的结算单不允许修改！"); return;
            }
            RemovePayDocPayDetail(e.Item.ItemIndex);
            RebindPayDocPayDetail();
        }
        else if (e.CommandName.ToLower() == "upt")
        {
            try
            {
                TextBox txtAmount;
                decimal payAmount = 0;
                for (int i = 0; i < dlistPayDocPayDetail.Items.Count; i++)
                {
                    txtAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
                    payAmount += Convert.ToDecimal(txtAmount.Text);
                }

                TextBox txtSettleAmount = (TextBox)dlistPayDoc.Items[0].FindControl("txtSettleAmount");
                TextBox txtPayAmount = (TextBox)dlistPayDoc.Items[0].FindControl("txtPayAmount");
                TextBox txtSubAmount = (TextBox)dlistPayDoc.Items[0].FindControl("txtSubAmount");


                txtPayAmount.Text = String.Format("{0:0.00}", payAmount);
                txtSubAmount.Text = String.Format("{0:0.00}", payAmount - Convert.ToDecimal(txtSettleAmount.Text));
            }
            catch (Exception ex)
            {
                Share.Alert(this.Page, ex.Message);
                //ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "click", "alert('" + ex.Message + "')", true);
            }
        }

    }

    protected void dlistPayDoc_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            TextBox txtSettleAmount = (TextBox)e.Item.FindControl("txtSettleAmount");
            TextBox txtPayAmount = (TextBox)e.Item.FindControl("txtPayAmount");
            TextBox txtSubAmount = (TextBox)e.Item.FindControl("txtSubAmount");
            TextBox txtNotes = (TextBox)e.Item.FindControl("txtNotes");

            if (this.IsCheck == "1")
            {
                txtSettleAmount.Enabled = false;
                txtPayAmount.Enabled = false;
                txtSubAmount.Enabled = false;
                txtNotes.Enabled = false;
            }
        }
    }

    protected void dlistPayDocDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            TextBox txtAmount = (TextBox)e.Item.FindControl("txtAmount");
            TextBox txtSubAmount = (TextBox)e.Item.FindControl("txtSubAmount");
            TextBox txtNotes = (TextBox)e.Item.FindControl("txtNotes");
            Button btnDelete = (Button)e.Item.FindControl("btnDelete");

            if (this.IsCheck == "1")
            {
                txtAmount.Enabled = false;
                txtSubAmount.Enabled = false;
                txtNotes.Enabled = false;
                btnDelete.Enabled = false;
            }

            Button btnUpdateClearAmount = (Button)e.Item.FindControl("btnUpdateClearAmount");
            txtAmount.Attributes.Add("onblur", btnUpdateClearAmount.ClientID + ".click();");

        }
    }

    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("Settlement.aspx");
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("700100", "00003"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }

        bool result = new BLL.PAYDOC().Delete(this.Code);
        if (result)
        {
            Response.Write("<script>alert('删除成功！');window.location.href='settlement.aspx'</script>");
        }
        else
        {
            Response.Write("<script>alert('删除失败！');</script>");           
        }
    }
}
